const News = require("../model/news");
const { Op } = require("sequelize");

module.exports = class NewsManager {
  static async addNews(news) {
    const result = await News.create(news);
    return result.toJSON;
  }

  static async delNew(id) {
    const result = await News.destroy({
      where: {
        id: id,
      },
    });
  }

  static async updateNews(id, news) {
    await News.update(news, {
      where: {
        id: id,
      },
    });
    const result = await News.findOne({
      where: {
        id: id,
      },
    });
    return result;
  }

  static async getAllNews() {
    const result = await News.findAll();
    return result;
  }

  static async getNewsById(id) {
    const result = await News.findOne({
      where: {
        id: id,
      },
    });
    return result;
  }

  static async find(
    page = 1,
    limit = 10,
    type,
    title,
    publishTime,
    publishName
  ) {
    const where = {};
    if (type) {
      where.type = type;
    }
    if (publishName) {
      where.publishName = {
        [Op.like]: `%${publishName}%`,
      };
    }
    if (title) {
      where.title = {
        [Op.like]: `%${title}%`,
      };
    }
    if (publishTime && publishTime.length === 2) {
      where.publishTime = {
        [Op.between]: [publishTime[0], publishTime[1]],
      };
    }
    const result = await News.findAndCountAll({
      where: where,
      offset: (page - 1) * parseInt(limit, 10),
      limit: parseInt(limit, 10),
      order: [["createdAt", "DESC"]],
    });
    return JSON.parse(JSON.stringify(result));
  }
};
